// 资源管理 Store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Resource, ResourceProduction, ResourceCost, ResourceStorage, MarketPrice } from '@/types'
import { BASIC_RESOURCES, INDUSTRIAL_RESOURCES, SPECIAL_RESOURCES } from '@/types'

export const useResourcesStore = defineStore('resources', () => {
  // 状态
  const resources = ref<Record<string, Resource>>({})
  const production = ref<Record<string, ResourceProduction>>({})
  const storage = ref<Record<string, ResourceStorage>>({})
  const marketPrices = ref<Record<string, MarketPrice>>({})
  const isInitialized = ref(false)

  // 计算属性
  const totalResources = computed(() => {
    return Object.values(resources.value).reduce((total, resource) => {
      total[resource.id] = resource.amount
      return total
    }, {} as Record<string, number>)
  })

  const totalProduction = computed(() => {
    return Object.values(production.value).reduce((total, prod) => {
      total[prod.resourceId] = (total[prod.resourceId] || 0) + prod.rate
      return total
    }, {} as Record<string, number>)
  })

  const storageUtilization = computed(() => {
    return Object.entries(resources.value).reduce((util, [id, resource]) => {
      const storageInfo = storage.value[id]
      if (storageInfo) {
        util[id] = (resource.amount / storageInfo.capacity) * 100
      }
      return util
    }, {} as Record<string, number>)
  })

  const resourcesByCategory = computed(() => {
    const categorized = {
      basic: [] as Resource[],
      industrial: [] as Resource[],
      special: [] as Resource[]
    }

    Object.values(resources.value).forEach(resource => {
      if (Object.values(BASIC_RESOURCES).includes(resource.id as any)) {
        categorized.basic.push(resource)
      } else if (Object.values(INDUSTRIAL_RESOURCES).includes(resource.id as any)) {
        categorized.industrial.push(resource)
      } else if (Object.values(SPECIAL_RESOURCES).includes(resource.id as any)) {
        categorized.special.push(resource)
      }
    })

    return categorized
  })

  // 动作
  function initializeResources() {
    // 初始化基础资源
    Object.values(BASIC_RESOURCES).forEach(resourceId => {
      resources.value[resourceId] = {
        id: resourceId,
        name: getResourceName(resourceId),
        category: 'basic',
        amount: getInitialAmount(resourceId), // 根据资源类型设置初始值
        rarity: 'common',
        description: getResourceDescription(resourceId),
        icon: `icon-${resourceId}`
      }

      storage.value[resourceId] = {
        resourceId,
        capacity: getInitialCapacity(resourceId),
        used: getInitialAmount(resourceId),
        efficiency: 1.0
      }
    })

    // 初始化工业资源
    Object.values(INDUSTRIAL_RESOURCES).forEach(resourceId => {
      resources.value[resourceId] = {
        id: resourceId,
        name: getResourceName(resourceId),
        category: 'industrial',
        amount: 0,
        rarity: 'uncommon',
        description: getResourceDescription(resourceId),
        icon: `icon-${resourceId}`
      }

      storage.value[resourceId] = {
        resourceId,
        capacity: 5000,
        used: 0,
        efficiency: 1.0
      }
    })

    // 初始化特殊资源
    Object.values(SPECIAL_RESOURCES).forEach(resourceId => {
      resources.value[resourceId] = {
        id: resourceId,
        name: getResourceName(resourceId),
        category: 'special',
        amount: 0,
        rarity: 'rare',
        description: getResourceDescription(resourceId),
        icon: `icon-${resourceId}`
      }

      storage.value[resourceId] = {
        resourceId,
        capacity: 1000,
        used: 0,
        efficiency: 1.0
      }
    })

    // 添加初始生产速率
    initializeBasicProduction()

    // 标记初始化完成
    isInitialized.value = true
    console.log('Resources initialized successfully')
  }

  // 获取初始资源数量
  function getInitialAmount(resourceId: string): number {
    const initialAmounts: Record<string, number> = {
      [BASIC_RESOURCES.POPULATION]: 100,    // 初始人口100
      [BASIC_RESOURCES.ENERGY]: 1000,       // 初始能源1000
      [BASIC_RESOURCES.FOOD]: 5000,         // 初始食物5000
      [BASIC_RESOURCES.WATER]: 3000,        // 初始水3000
      [BASIC_RESOURCES.OXYGEN]: 2000,       // 初始氧气2000
      [BASIC_RESOURCES.METAL]: 2000,        // 初始金属2000
      [BASIC_RESOURCES.CRYSTAL]: 500        // 初始水晶500
    }
    return initialAmounts[resourceId] || 1000
  }

  // 获取初始存储容量
  function getInitialCapacity(resourceId: string): number {
    const initialCapacities: Record<string, number> = {
      [BASIC_RESOURCES.POPULATION]: 1000,   // 人口容量1000
      [BASIC_RESOURCES.ENERGY]: 10000,      // 能源容量10000
      [BASIC_RESOURCES.FOOD]: 50000,        // 食物容量50000
      [BASIC_RESOURCES.WATER]: 30000,       // 水容量30000
      [BASIC_RESOURCES.OXYGEN]: 20000,      // 氧气容量20000
      [BASIC_RESOURCES.METAL]: 20000,       // 金属容量20000
      [BASIC_RESOURCES.CRYSTAL]: 5000       // 水晶容量5000
    }
    return initialCapacities[resourceId] || 10000
  }

  // 初始化基础生产速率
  function initializeBasicProduction() {
    // 人口自然增长 - 每秒增长0.1%
    addProduction('base_population_growth', {
      resourceId: BASIC_RESOURCES.POPULATION,
      rate: 0.1, // 每秒0.1人口（基础增长）
      efficiency: 1.0,
      isActive: true
    })

    // 基础能源生产 - 初始太阳能板
    addProduction('base_energy_production', {
      resourceId: BASIC_RESOURCES.ENERGY,
      rate: 5, // 每秒5能源
      efficiency: 1.0,
      isActive: true
    })

    // 基础食物生产 - 初始农场
    addProduction('base_food_production', {
      resourceId: BASIC_RESOURCES.FOOD,
      rate: 3, // 每秒3食物
      efficiency: 1.0,
      isActive: true
    })

    // 基础水生产 - 水循环系统
    addProduction('base_water_production', {
      resourceId: BASIC_RESOURCES.WATER,
      rate: 2, // 每秒2水
      efficiency: 1.0,
      isActive: true
    })

    // 基础氧气生产 - 氧气循环系统
    addProduction('base_oxygen_production', {
      resourceId: BASIC_RESOURCES.OXYGEN,
      rate: 1.5, // 每秒1.5氧气
      efficiency: 1.0,
      isActive: true
    })

    // 基础金属开采 - 初始矿场
    addProduction('base_metal_production', {
      resourceId: BASIC_RESOURCES.METAL,
      rate: 1, // 每秒1金属
      efficiency: 1.0,
      isActive: true
    })

    // 基础水晶开采 - 初始水晶矿
    addProduction('base_crystal_production', {
      resourceId: BASIC_RESOURCES.CRYSTAL,
      rate: 0.2, // 每秒0.2水晶
      efficiency: 1.0,
      isActive: true
    })

    console.log('Basic production initialized')
  }

  function addResource(resourceId: string, amount: number): boolean {
    const resource = resources.value[resourceId]
    const storageInfo = storage.value[resourceId]
    
    if (!resource || !storageInfo) return false

    const availableSpace = storageInfo.capacity - resource.amount
    const actualAmount = Math.min(amount, availableSpace)
    
    if (actualAmount > 0) {
      resource.amount += actualAmount
      storageInfo.used = resource.amount
      return true
    }
    
    return false
  }

  function removeResource(resourceId: string, amount: number): boolean {
    const resource = resources.value[resourceId]
    
    if (!resource || resource.amount < amount) return false

    resource.amount -= amount
    const storageInfo = storage.value[resourceId]
    if (storageInfo) {
      storageInfo.used = resource.amount
    }
    
    return true
  }

  function canAfford(costs: ResourceCost[]): boolean {
    return costs.every(cost => {
      const resource = resources.value[cost.resourceId]
      return resource && resource.amount >= cost.amount
    })
  }

  function payCosts(costs: ResourceCost[]): boolean {
    if (!canAfford(costs)) return false

    costs.forEach(cost => {
      removeResource(cost.resourceId, cost.amount)
    })

    return true
  }

  function addProduction(sourceId: string, resourceProduction: ResourceProduction) {
    const key = `${sourceId}_${resourceProduction.resourceId}`
    production.value[key] = resourceProduction
  }

  function removeProduction(sourceId: string, resourceId: string) {
    const key = `${sourceId}_${resourceId}`
    delete production.value[key]
  }

  function updateProduction(deltaTime: number) {
    Object.values(production.value).forEach(prod => {
      if (prod.isActive) {
        const amount = (prod.rate * deltaTime) / 1000 // 转换为秒
        addResource(prod.resourceId, amount)
      }
    })
  }

  function upgradeStorage(resourceId: string, newCapacity: number) {
    const storageInfo = storage.value[resourceId]
    if (storageInfo) {
      storageInfo.capacity = newCapacity
    }
  }

  function getResource(resourceId: string): Resource | undefined {
    return resources.value[resourceId]
  }

  function getResourceAmount(resourceId: string): number {
    if (!isInitialized.value) {
      console.warn('Resources not initialized yet, returning 0 for', resourceId)
      return 0
    }
    return resources.value[resourceId]?.amount || 0
  }

  function getResourceProduction(resourceId: string): number {
    return totalProduction.value[resourceId] || 0
  }

  function getResourceStorage(resourceId: string): number {
    return storage.value[resourceId]?.capacity || 0
  }

  function setMarketPrice(resourceId: string, price: MarketPrice) {
    marketPrices.value[resourceId] = price
  }

  // 辅助函数
  function getResourceName(resourceId: string): string {
    const names: Record<string, string> = {
      [BASIC_RESOURCES.METAL]: '金属',
      [BASIC_RESOURCES.CRYSTAL]: '水晶',
      [BASIC_RESOURCES.GAS]: '气体',
      [BASIC_RESOURCES.ENERGY]: '能量',
      [BASIC_RESOURCES.FOOD]: '食物',
      [BASIC_RESOURCES.WATER]: '水',
      [BASIC_RESOURCES.POPULATION]: '人口',
      [INDUSTRIAL_RESOURCES.ALLOY]: '合金',
      [INDUSTRIAL_RESOURCES.ELECTRONICS]: '电子元件',
      [INDUSTRIAL_RESOURCES.CHEMICALS]: '化学品',
      [INDUSTRIAL_RESOURCES.COMPOSITES]: '复合材料',
      [INDUSTRIAL_RESOURCES.NANOMATERIALS]: '纳米材料',
      [INDUSTRIAL_RESOURCES.QUANTUM_CORES]: '量子核心',
      [INDUSTRIAL_RESOURCES.BIOTECH]: '生物技术',
      [INDUSTRIAL_RESOURCES.AI_CORES]: 'AI核心',
      [SPECIAL_RESOURCES.ANTIMATTER]: '反物质',
      [SPECIAL_RESOURCES.DARK_MATTER]: '暗物质',
      [SPECIAL_RESOURCES.EXOTIC_MATTER]: '奇异物质',
      [SPECIAL_RESOURCES.TEMPORAL_CRYSTALS]: '时间水晶',
      [SPECIAL_RESOURCES.PSIONIC_ENERGY]: '灵能',
      [SPECIAL_RESOURCES.ZERO_POINT_ENERGY]: '零点能'
    }
    return names[resourceId] || resourceId
  }

  function getResourceDescription(resourceId: string): string {
    const descriptions: Record<string, string> = {
      [BASIC_RESOURCES.METAL]: '基础建设材料',
      [BASIC_RESOURCES.CRYSTAL]: '高科技设备原料',
      [BASIC_RESOURCES.GAS]: '能源和化工原料',
      [BASIC_RESOURCES.ENERGY]: '驱动一切设施运转',
      [BASIC_RESOURCES.FOOD]: '维持人口生存',
      [BASIC_RESOURCES.WATER]: '生命之源',
      [BASIC_RESOURCES.POPULATION]: '文明的基础',
      [INDUSTRIAL_RESOURCES.ALLOY]: '高强度建筑材料',
      [INDUSTRIAL_RESOURCES.ELECTRONICS]: '精密设备核心',
      [INDUSTRIAL_RESOURCES.CHEMICALS]: '工业生产必需品',
      [INDUSTRIAL_RESOURCES.COMPOSITES]: '轻质高强材料',
      [INDUSTRIAL_RESOURCES.NANOMATERIALS]: '纳米级精密材料',
      [INDUSTRIAL_RESOURCES.QUANTUM_CORES]: '量子计算核心',
      [INDUSTRIAL_RESOURCES.BIOTECH]: '生物工程产品',
      [INDUSTRIAL_RESOURCES.AI_CORES]: '人工智能核心',
      [SPECIAL_RESOURCES.ANTIMATTER]: '终极能源',
      [SPECIAL_RESOURCES.DARK_MATTER]: '神秘宇宙物质',
      [SPECIAL_RESOURCES.EXOTIC_MATTER]: '超越物理定律的物质',
      [SPECIAL_RESOURCES.TEMPORAL_CRYSTALS]: '时间操控媒介',
      [SPECIAL_RESOURCES.PSIONIC_ENERGY]: '精神力量结晶',
      [SPECIAL_RESOURCES.ZERO_POINT_ENERGY]: '真空零点能量'
    }
    return descriptions[resourceId] || '未知资源'
  }

  return {
    // 状态
    resources,
    production,
    storage,
    marketPrices,
    isInitialized,
    
    // 计算属性
    totalResources,
    totalProduction,
    storageUtilization,
    resourcesByCategory,
    
    // 动作
    initializeResources,
    addResource,
    removeResource,
    canAfford,
    payCosts,
    addProduction,
    removeProduction,
    updateProduction,
    upgradeStorage,
    getResource,
    getResourceAmount,
    getResourceProduction,
    getResourceStorage,
    getResourceName,
    setMarketPrice
  }
})